import { createRouter, createWebHistory } from "vue-router";
import { getToken } from "@/utils/cookie";
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/oj/login",
      name: "login",
      component: () => import("../views/Login.vue"),
    },
    {
      path: "/",
      redirect: "/oj/login",  // redirect：当访问 / 路径时，自动跳转到 /oj/login 路径
    },
    {
      path: "/oj/layout",
      name: "layout",
      component: () => import("../views/Layout.vue"),
      children:[
        {
          path: "cuser",
          name: "cuser",
          component: () => import("../views/Cuser.vue"),
        },
        {
          path: "exam",
          name: "exam",
          component: () => import("../views/Exam.vue"),
        },
        {   
          path: "question",
          name: "question",
          component: () => import("../views/Question.vue"),
        },
        {
          path: 'updateExam',
          name: 'updateExam',
          component: () => import('../views/UpdateExam.vue')
        },
        {
          path: 'cuser',
          name: 'cuser',
          component: () => import('@/views/Cuser.vue')
        }
      ]
    }
  ],
});


// 全局路由前置守卫
// to表示要跳转到哪里去，from表示从哪里跳转过来的 next表示放行，是一个方法 
router.beforeEach((to, from, next) => {
  if(getToken()) {  // 判断是否有token
    if(to.path === '/oj/login') {
      next({path: '/oj/layout'})  // 跳转到layout页面
    } else {
      next()  // 放行
    }
  } else {
    if(to.path !== '/oj/login') {
      next({path: '/oj/login'})  // 跳转到login页面
    } else {
      next()  // 放行
    }
  }
});

export default router;
